public class SparseTest {
    public static void main(String[] args) {
        //1.构建一个数组
        int arr[][] = new int[11][11];
        arr[1][2] = 1;
        arr[2][3] = 2;
        arr[3][5] = 2;
        for (int[] row : arr) {
            for (int data:row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        //②将二维数组这换为稀疏数组
        int sum=0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i][j] != 0){
                    sum++;
                }
            }
        }
        //③创建对应的稀疏数组,列数固定为3，第一行为原数组的行列数及有效数据个数
        int sparseArr[][] = new int[sum+1][3];
        sparseArr[0][0] = arr.length;
        sparseArr[0][1] = arr.length;
        sparseArr[0][2] = sum;
        int count = 0;//用于记录是第几个非零数据
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i][j] != 0){
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = arr[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("得到的稀疏数组为：");
        for (int i = 0; i < sparseArr.length; i++){
            System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
        }

        //稀疏数组转为原二维数组
        int originArr[][] = new int[sparseArr[0][1]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            originArr[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }

        //输出原二维数组
        System.out.println("原二维数组为：");
        for(int[] row : originArr){
            for(int data : row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }
}
